package com.zhugang.week11;

/**
 * @program algorithms
 * @description: longestCommonSubsequence
 * @author: chanzhugang
 * @create: 2022/09/05 16:25
 */
public class LongestCommonSubsequence {

    /**
     * 1143 最长公共子序列
     *
     * @param text1
     * @param text2
     * @return
     */
    public int longestCommonSubsequence(String text1, String text2) {
        // 很难想
        // 子序列：原字符串不改变字符相对顺序删除某些字符（也可不删除）得到新的字符串
        // 公共子序列长度
        // dp[i][j]:表示长度为i的t1子串和长度是j的t2子串的最长公共子序列长度

        // dp[i][j] = max(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1] + 1), t1[i - 1] == t2[j - 1]
        // dp[i][j] = max(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]), t1[i - 1] != t2[j - 1]

        int n = text1.length();
        int m = text2.length();
        char[] t1 = text1.toCharArray();
        char[] t2 = text2.toCharArray();

        int[][] dp = new int[n + 1][m + 1];
        for (int j = 0; j <= m; j++) {
            // 初始化第一行
            dp[0][j] = 0;
        }
        for (int i = 0; i <= n; i++) {
            // 初始化第一列
            dp[i][0] = 0;
        }

        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (t1[i - 1] == t2[j - 1]) {
                    // 匹配状态过来的+1 ， 是从上、左、左上转来的
                    dp[i][j] = max3(dp[i - 1][j - 1] + 1, dp[i - 1][j], dp[i][j - 1]);
                } else {
                    dp[i][j] = max3(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[n][m];
    }

    private int max3(int a, int b, int c) {
        int maxv = a;
        if (maxv < b) {
            maxv = b;
        }
        if (maxv < c) {
            maxv = c;
        }
        return maxv;
    }
}